package com.fingard.dsp.bank.directbank.gxnx02;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/10/10.
 */
public class GXNX02Base extends DirectBase implements ITcpClient {
    private static final String STR_FORMAT = "00000000";
    DecimalFormat decimalFormat = new DecimalFormat(STR_FORMAT);
    private String separator = "|";

    public Map<String, Object> writerPayFileContext(ReqBatPayRec p_req1988) throws Exception {
        /**
         * 总笔数 | 代付总金额|       以"\n"为结束符
         * 业务流水号|用户号｜银行账号|户名|证件类型｜证件号码｜金额|   以"\n"为结束符
         */
        Map<String, Object> resultAndfileContext = new HashMap<String, Object>();
        StringBuilder msgXml = new StringBuilder();
        //第一行
        msgXml.append(p_req1988.totalNum).append(separator);//总笔数
        msgXml.append(p_req1988.totalAmt).append(separator);//总代付总金额
        msgXml.append("\n");
        int tmpCount = 0;
        while (p_req1988.readRecord()) {
            tmpCount++;
//            String tranCode = "";//交易代号
//            if ("1".equals(p_req1988.readedDetail.sameBnk)) {
//                tranCode = "2001S";
//            } else if ("0".equals(p_req1988.readedDetail.sameBnk)) {
//                tranCode = "2002S";
//            }
//            String reqNo = Format.DateTime14Format.format(new Date()) + tranCode + getQryTransID();
            msgXml.append(p_req1988.readedDetail.abstractATS).append(separator);//业务流水号(这里存对账码)
            msgXml.append(separator);//用户号??
            msgXml.append(p_req1988.readedDetail.recAct).append(separator);//银行账号
            msgXml.append(p_req1988.readedDetail.recName).append(separator);//户名
            msgXml.append(convertCertTypeToBank(p_req1988.readedDetail.certType)).append(separator);//证件类型（可空）
            msgXml.append(p_req1988.readedDetail.certNum).append(separator);//证件号码（可空）
            msgXml.append(p_req1988.readedDetail.payAmount).append(separator);//金额
            msgXml.append("\n");
        }
        if (tmpCount != Integer.parseInt(p_req1988.totalNum)) {
            resultAndfileContext.put("result", "false");
        } else {
            resultAndfileContext.put("result", "true");
        }
        resultAndfileContext.put("fileContext", msgXml);
        return resultAndfileContext;
    }

    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength >= 8) {
                String tmpHead = new String(p_receiver.recBytes, 0, 8, getCharset2());
                WriteBankLogStep3(tmpHead);
                p_receiver.contentLength = Integer.parseInt(tmpHead.trim()) - 8;
                p_receiver.contentStartIndex = 0;
            }
        }
    }

    private static TransIDHelper idHelper = new TransIDHelper(1, 99999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.Time9Format.format(tmpDateNow).substring(6) + idHelper.getNextIDStr();
    }


    private static TransIDHelper idHelper2 = new TransIDHelper(1, 99);

    protected String getID() {
        return idHelper2.getNextIDStr();
    }

    protected String getCharset2() {
        return "GB2312";
    }

    protected void writeCommonHeader1(XmlTextWriter xmlWriter, GXNX02Header p_bankHeader) throws Exception {
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset2() + "\"?>");
        xmlWriter.writeStartElement("GXNXYQ");
        xmlWriter.writeStartElement("REQ");
        xmlWriter.writeStartElement("REQHEAD");
        xmlWriter.writeElementString("TranCode", p_bankHeader.tranCode);
        xmlWriter.writeElementString("UserID", bankFront.org);
        xmlWriter.writeElementString("ErpNo", bankFront.operator);
        xmlWriter.writeElementString("TranSeq", p_bankHeader.tranSeq);
        Date date = new Date();
        xmlWriter.writeElementString("TranDate", Format.Date8Format.format(date));
        xmlWriter.writeElementString("TranTime", Format.Time6Format.format(date));
        xmlWriter.writeElementString("ChannelID", "B2");
        xmlWriter.writeEndElement();

    }

    protected String[] sendToBank1(String xml) throws Exception{
        xml = String.format("%08d%s",xml.getBytes(getCharset2()).length+8,xml);
        WriteBankLogStep2(xml);
        String result[]={"",""} ;
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP,Integer.valueOf(bankFront.serverPort),this);
        TcpReceiver tcpReceiver = tmpClient.sendMessage(xml.getBytes(getCharset2()));
        result[0] = tcpReceiver.connState;
        if(result[0].length()>0){
            result[1] = tcpReceiver.connMsg;
            return result;
        }
        if(tcpReceiver.recBytes!=null){
            result[1] = new String (tcpReceiver.recBytes,0,tcpReceiver.recBytes.length,getCharset2() );
        }
        WriteBankLogStep3(result[1]);
        if (result[1].length()>8){
            result[1] = result[1].substring(8);
        }
        return result;
    }

    protected static boolean isActiveRetCode(String retCode) {
        if (retCode != null) {
            if (retCode.equals("0000")) {
                return true;
            }
        }
        return false;
    }
}
